package com.sl.au.controller;

import com.sl.au.entity.Account;
import com.sl.au.entity.BusinesssellerAuthentication;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.BussinessCheck;
import com.sl.au.entity.BussinessInspection;
import com.sl.au.entity.Evaluate;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventRegisterAndTaskView;
import com.sl.au.entity.EventRegisterTask;
import com.sl.au.entity.Grading;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.GridUserDetails;
import com.sl.au.entity.Module;
import com.sl.au.entity.Option;
import com.sl.au.entity.Part;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.PartBaseInfo;
import com.sl.au.entity.PartsType;
import com.sl.au.entity.User;
import com.sl.au.entity.UserTrajectory;
import com.sl.au.entity.ViewForEventRegisterTask;
import com.sl.au.entity.ViewForEventReportTask;
import com.sl.au.service.SectionService;
import com.sl.au.service.UserService;
import com.sl.au.service.UserTrajectoryService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MeanGpsUtil;
import com.sl.utils.LngLat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.service.AttachmentService;
import com.sl.au.service.BusinesssellerAuthenticationService;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussinessCheckService;
import com.sl.au.service.BussinessInspectionService;
import com.sl.au.service.EvaluateService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.EventReportService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.GridUserDetailsService;
import com.sl.au.service.IndexService;
import com.sl.au.service.OptionService;
import com.sl.au.service.PartBaseInfoService;
import com.sl.au.service.PartService;
import com.sl.au.service.PartsTypeService;
import com.sl.au.service.HierarchyService;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/ui/index")
public class IndexController extends BaseController {


	@Autowired
	SectionService sectionService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	IndexService indexService;
	@Autowired
	UserService userService;
	@Autowired
	PartService	partService;
	@Autowired
	PartBaseInfoService partBaseInfoService;
	@Autowired
	GridAreaInfoService gridAreaInfoService;
	@Autowired
	GridUserDetailsService gridUserDetailsService;
	@Autowired
	EventReportService eventReportService;
	@Autowired
	OptionService optionService;
	@Autowired
	BusinesssellerAuthenticationService businesssellerAuthenticationService;
	@Autowired
	EvaluateService evaluateService;
	@Autowired
	BussinessInspectionService bussinessInspectionService;
	@Autowired
	BussinessCheckService bussinessCheckService;
	@Autowired
	BusinesssellerBaseInfoService businesssellerBaseInfoService;
	@Autowired
	HierarchyService hierarchyService;
	@Autowired
	UserTrajectoryService userTrajectoryService;
	
	@Autowired
	EventRegisterService eventRegisterService;
	
    
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		Account account =this.getMyAccount();
		String URL ="eventRegister";
		Boolean isOwner = false;
		for (Module m : account.getRole().getModules()) {
			if (URL.contains(m.getTarget().replace("?device=mobile", ""))) {
				isOwner = true;
				break;
			}
			if (!m.getTarget().equals("#")) {
				String model = m.getTarget().split("/")[2];
				if (URL.contains(model))
					isOwner = true;
			}
		}
		
		if(isOwner){
			ModelAndView modelAndView = createLayoutView("index/indexmap");
			return modelAndView;
		}else{
			ModelAndView modelAndView = createLayoutView("index/indexmap");
			return modelAndView;
		}
	
	}
	/**
	 * 获取报警数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAlarmData",method = RequestMethod.GET)
	public Map<String,Object> getAlarmData(HttpServletRequest request){
		Map<String,Object> map = this.eventReportService.getStatistics();
		return map;
	}
	/**
	 * 获取配置数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getConfigData",method = RequestMethod.GET)
	public Map<String,Object> getConfigData(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		
		//查找统计数据
		Map<String,Object> statis=this.eventReportService.getStatistics();
		map.put("statis", statis);
		//初始化部件数据
		//List<Part> parts = partService.getChildrenPartByKey(0, Integer.MAX_VALUE, "0", null, null, null);
		List<Map<String, Object>> parts = partService.getNextNode("0");
		map.put("parts", parts);
		
		//初始化网格数据
		List<Option> options = optionService.getRepository().findByGroup("元素类型");
		map.put("options", options);
		
		//初始化部门数据
		List<Map<String, Object>> depts=this.hierarchyService.getNextNode("0");
		map.put("depts", depts);
		
		return map;
	}


	@RequestMapping(value="getPartNext/{id}",method = RequestMethod.GET)
	public Map<String,Object> getPartNext(@PathVariable("id") String id){
		Map<String,Object> map = new HashMap<String,Object>();
//		List<Part> parts = partService.getChildrenPartByKey(0, Integer.MAX_VALUE, id, null, null, null);
//		map.put("parts", parts);
		List<Map<String, Object>> parts = partService.getNextNode(id);
		map.put("parts", parts);
		return map;
	}
	
	@RequestMapping(value="getDeptNext/{id}",method = RequestMethod.GET)
	public Map<String,Object> getDeptNext(@PathVariable("id") String id){
		Map<String,Object> map = new HashMap<String,Object>();
//		List<Part> parts = partService.getChildrenPartByKey(0, Integer.MAX_VALUE, id, null, null, null);
//		map.put("parts", parts);
		List<Map<String, Object>> depts = this.hierarchyService.getNextNode(id);
		map.put("depts", depts);
		return map;
	}
	
	@RequestMapping(value="getPartView/{partId}", method = RequestMethod.GET)
	public ModelAndView getPartView(@PathVariable("partId") String partId) {
		ModelAndView modelAndView = createLayoutView("index/indexmap");
		modelAndView.setViewName("index/indexInfo/QTouchIndexPartsMsg");
		modelAndView.addObject("partId", partId);
		return modelAndView;
	}

	@RequestMapping(value="getPartInfo/{partId}", method = RequestMethod.GET)
	public Map<String,Object> getPartInfo(@PathVariable("partId") String partId) {
		Map<String,Object> map = new HashMap<String,Object>();
		PartBaseInfo part = partBaseInfoService.getRepository().findOne(partId);
		map.put("part", part);
		return map;
	}

	@RequestMapping(value="getGridView/{gridId}", method = RequestMethod.GET)
	public ModelAndView getGridView(@PathVariable("gridId") String gridId) {
		ModelAndView modelAndView = createLayoutView("index/indexmap");
		modelAndView.setViewName("index/indexInfo/QTouchIndexGridMsg");
		modelAndView.addObject("gridId", gridId);
		return modelAndView;
	}
	@RequestMapping(value="getDeptFollowView/{deptId}", method = RequestMethod.GET)
	public ModelAndView getDeptFollowView(@PathVariable("deptId") String deptId) {
		ModelAndView modelAndView = createLayoutView("index/indexmap");
		modelAndView.setViewName("index/indexInfo/QTouchIndexDeptFollow");
		modelAndView.addObject("deptId", deptId);
		return modelAndView;
	}
	@RequestMapping(value = "getUserInfoList/{deptId}", method = RequestMethod.GET)
	public Map<String, Object> getUserInfoList(HttpServletRequest request,@PathVariable("deptId") String deptId) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<User> users =null;
		int count=0;
		if(org.springframework.util.StringUtils.hasText(deptId)&&!deptId.equals("all"))
		{
			users=userService.getUsersByDept(start, length, key, deptId, null, null);
			count=userService.getCountByDept(deptId, key);
		}else if(deptId.equals("all")){
			if (org.springframework.util.StringUtils.hasText(key)){
				users=userService.getUsers(start, length, key, null, null);		
			}else {
				users=userService.getPage(start, length, null, null, null);			
			}
			count=userService.getCount(key);
		}
		
		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value="getGridInfo/{gridId}", method = RequestMethod.GET)
	public Map<String,Object> getGridInfo(@PathVariable("gridId") String gridId) {
		Map<String,Object> map = new HashMap<String,Object>();
		GridAreaInfo grid = gridAreaInfoService.getRepository().findOne(gridId);
		map.put("grid", grid);
		
		List<Grading> gradings = gridUserDetailsService.getRepository().getGradingByGrid(gridId);
		map.put("gradings", gradings);
		
		List<GridUserDetails> gridUsers = gridUserDetailsService.getRepository().getAllByGrid(gridId);
		map.put("gridUsers", gridUsers);
		
		
//		Date begin = ExdeUtil.getTodayBegin();
		Date begin = ExdeUtil.getTodayBefore("year", "1");
		Date end = ExdeUtil.getTodayEnd();
		List<ViewForEventReportTask> eventReports = eventReportService.getReportByGrid(gridId, "已受理", begin, end);
		map.put("eventReports", eventReports);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap = eventReportService.getReportDataByGrid(gridId, "已受理", begin, end);
		map.put("analysisData", resultMap);
		
		return map;
	}
	
	@RequestMapping(value="getPartList/{partId}", method = RequestMethod.GET)
	public Map<String,Object> getPartList(@PathVariable("partId") String partId) {
		Map<String,Object> map = new HashMap<String,Object>();
		List<PartBaseInfo> parts = partBaseInfoService.getRepository().getAllByPartType(partId);
		map.put("parts", parts);
		return map;
	}
	
	@RequestMapping(value="getUserListByIds/{ids}", method = RequestMethod.GET)
	public Map<String,Object> getUserListByIds(@PathVariable("ids") String ids) {
		Map<String,Object> map = new HashMap<String,Object>();
		String[] list=ids.split(",");
		List<String> idsList = new ArrayList();
		Map<String, List<UserTrajectory>> tempTrajectory =  new HashMap<String, List<UserTrajectory>>();
		
		Map<String, User> tempUser =  new HashMap<String, User>();
		for(int i=0;i<list.length;i++)
		{
			idsList.add(list[i]);
			List<UserTrajectory> tempLine = new ArrayList<UserTrajectory>();
			tempTrajectory.put(list[i], tempLine);
			tempUser.put(list[i], null);
		}
		List<UserTrajectory> users =this.userTrajectoryService.getRepository().getAllByUserIds(idsList);
		for(UserTrajectory ut: users) {
			User u = ut.getUser();
			String uId = u.getId();
			tempTrajectory.get(uId).add(ut);
			if(tempUser.get(uId) == null) {
				tempUser.put(uId, u);
			}
		}
		List<UserTrajectory> users2 = new ArrayList<UserTrajectory>();
		
		for(int i=0;i<list.length;i++){
			List<UserTrajectory> mUsers = tempTrajectory.get(list[i]);
			User mUser = tempUser.get(list[i]);
			ArrayList<LngLat> mLine = new ArrayList<LngLat>();
			Date lDate = null;
			for(int j=0;j<mUsers.size();j++) {
				Date tDate = mUsers.get(j).getTrajectoryTime();
				if(lDate != null && tDate.getTime() - lDate.getTime() >= 1000 * 60 * 5) {
					setUserTrajectory(users2,mLine,mUser);
					mLine.clear();
				}
				lDate = tDate;
				LngLat p = new LngLat(mUsers.get(j).getLongitude(), mUsers.get(j).getLatitude());
				mLine.add(p);
			}
			setUserTrajectory(users2,mLine,mUser);
		}
		
		map.put("users", users2);
		return map;
	}
	
	public void setUserTrajectory(List<UserTrajectory> users,ArrayList<LngLat> mLine,User mUser) {
		System.out.println("新增轨迹");
		ArrayList<LngLat> gLine = new ArrayList<LngLat>();
		if(mLine.size() > 100) {
			MeanGpsUtil gpsUtil = new MeanGpsUtil(mLine);
			gLine = gpsUtil.meangps();
		}else {
			gLine.addAll(mLine);
		}
		
		for(int k=0;k<gLine.size();k++) {
			UserTrajectory ut = new UserTrajectory();
			ut.setUser(mUser);
			ut.setLatitude(gLine.get(k).latitude);
			ut.setLongitude(gLine.get(k).longitude);
			users.add(ut);
		}
	}
	
	@RequestMapping(value="getUserList/{deptId}", method = RequestMethod.GET)
	public Map<String,Object> getUserList(@PathVariable("deptId") String deptId) {
		Map<String,Object> map = new HashMap<String,Object>();
		Hierarchy dept =this.hierarchyService.getRepository().findOne(deptId);
		List<UserTrajectory> users =this.userTrajectoryService.getRepository().getAllByDept(dept);
		map.put("users", users);
		return map;
	}
	@RequestMapping(value="getgridList/{gridTypeId}", method = RequestMethod.GET)
	public Map<String,Object> getGridList(@PathVariable("gridTypeId") String gridTypeId) {
		Map<String,Object> map = new HashMap<String,Object>();
		Option options =this.optionService.getRepository().findOne(gridTypeId);
		List<GridAreaInfo> grids =  this.gridAreaInfoService.getRepository().getPageWithTypeName(options.getTitle());
		map.put("grids", grids);
		return map;
	}

	@RequestMapping(value="getVideoPartList", method = RequestMethod.GET)
	public Map<String,Object> getVideoPartList() {
		Map<String,Object> map = new HashMap<String,Object>();
		List<PartBaseInfo> videos = partBaseInfoService.getRepository().findVideoPartInfo();
		map.put("videos", videos);
		return map;
	}

	@RequestMapping(value="getShowList", method = RequestMethod.GET)
	public Map<String,Object> getShowList() {
		Map<String,Object> map = new HashMap<String,Object>();
		//List<BusinesssellerAuthentication> shops = businesssellerAuthenticationService.getRepository().findAll();
		List<BusinesssellerBaseInfo> shops = businesssellerBaseInfoService.getRepository().findAll();
		map.put("shops", shops);
		return map;
	}
	
	@RequestMapping(value="getShopView/{shopId}", method = RequestMethod.GET)
	public ModelAndView getShopView(@PathVariable("shopId") String shopId) {
		ModelAndView modelAndView = createLayoutView("index/indexmap");
		modelAndView.setViewName("index/indexInfo/QTouchIndexShopMsg");
		modelAndView.addObject("shopId", shopId);
		return modelAndView;
	}
	
	@RequestMapping(value="getShowInfo/{shopId}", method = RequestMethod.GET)
	public Map<String,Object> getShowInfo(@PathVariable("shopId") String shopId) {
		Map<String,Object> map = new HashMap<String,Object>();
//		BusinesssellerAuthentication shop = businesssellerAuthenticationService.getRepository().getInfoById(shopId);
		BusinesssellerBaseInfo shop = businesssellerBaseInfoService.getRepository().findOne(shopId);
		Evaluate evaluate = evaluateService.getRepository().getInfoByBusinessseller(shopId);
		
		List<BussinessInspection> InspectionHistory = bussinessInspectionService.findByCheck(0, 10, shopId, null, null);
		List<BussinessInspection> Inspection = bussinessInspectionService.findByTimeAndUncheck(0, 10, shopId, null, null);
		
		List<BussinessCheck> CheckHistory = this.bussinessCheckService.getCheckHistory(0, 10, shopId, "checkDate");
		map.put("evaluate", evaluate);
		map.put("shop", shop);
		map.put("InspectionHistory", InspectionHistory);
		map.put("Inspection", Inspection);
		map.put("CheckHistory", CheckHistory);
		return map;
	}
	
	@RequestMapping(value="getPartRealInfo/{partId}", method = RequestMethod.GET)
	public Map<String,Object> getPartRealInfo(@PathVariable("partId") String partId) {
		Map<String,Object> map = new HashMap<String,Object>();
		PartBaseInfo part = partBaseInfoService.getRepository().findOne(partId);
		String deviceIdentify = part.getDeviceIdentify();
		indexService.getParts(deviceIdentify, map);
		return map;
	}
	
	@RequestMapping(value="getUserView/{userId}/{isFollow}", method = RequestMethod.GET)
	public ModelAndView getUserView(@PathVariable("userId") String userId,@PathVariable("isFollow") String isFollow) {
		ModelAndView modelAndView = new ModelAndView("index/indexInfo/QTouchIndexUserMsg");
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("isFollow", isFollow);
		return modelAndView;
	}
	
	@RequestMapping(value="getUserInfo/{userId}", method = RequestMethod.GET)
	public Map<String,Object> getUserInfo(@PathVariable("userId") String userId) {
		Map<String,Object> map = new HashMap<String,Object>();
		User user = userService.getRepository().findOne(userId);
		
		//待处理
		Option dealtWithOpt = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "处理中").get(0);
		List<ViewForEventRegisterTask> dealtWith = eventRegisterService.getPageByTaskStateAndOperate(0, 10, dealtWithOpt.getId(), userId, "", "eventTaskTime", Sort.Direction.DESC);
		
		//待接收
		Option receiveOpt = optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已分配").get(0);
		List<EventRegister> receive = eventRegisterService.getPageByStateAndGrid(0, 10, receiveOpt.getId(), userId, "", "createTime", Sort.Direction.DESC);
		
		map.put("user", user);
		map.put("dealtWith", dealtWith);
		map.put("receive", receive);
		
		return map;
	}
	
	
	@RequestMapping(value="getEventFollowView", method = RequestMethod.GET)
	public ModelAndView getEventFollowView() {
		ModelAndView modelAndView = createLayoutView("index/indexmap");
		modelAndView.setViewName("index/indexInfo/QTouchIndexEventFollow");
		return modelAndView;
	}
	
	@RequestMapping(value = "getEventInfoList", method = RequestMethod.GET)
	public Map<String, Object> getpage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		Option opt = optionService.getRepository().findByTitleAndGroup("处理中", "内部事件流转状态");
		String type = "";
		if(opt != null) {
			type = opt.getId();
		}
		List<ViewForEventRegisterTask> rvs = null;
		int count=0;
		
		count = this.eventRegisterService.getCountByTaskStateAndOperateUser(type,"",key);
		rvs=eventRegisterService.getPageByTaskStateAndOperate(start,length,type,"",key,"registerEventAccTime", Sort.Direction.DESC);
		
		map.put("data", rvs);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value="getEventUserListById/{id}", method = RequestMethod.GET)
	public Map<String,Object> getEventUserListByIds(@PathVariable("id") String id) {
		Map<String,Object> map = new HashMap<String,Object>();
		List<UserTrajectory> user =this.userTrajectoryService.getRepository().getUserId(id);
		map.put("users", user);
		return map;
	}
	
	@RequestMapping(value="refreashPartStatus/{partId}", method = RequestMethod.GET)
	public Map<String,Object> refreashPartStatus(@PathVariable("partId") String partId) {
		Map<String,Object> map = new HashMap<String,Object>();
		List<PartBaseInfo> parts = partBaseInfoService.getRepository().getAllByPartType(partId);
		List<PartBaseInfo> warnings = new ArrayList<PartBaseInfo>();
		for(PartBaseInfo part: parts) {
			String deviceIdentify = part.getDeviceIdentify();
			Map<String,Object> result = new HashMap<String,Object>();
			indexService.getParts(deviceIdentify, result);
			if(result.containsKey("count")) {
				int count = ExdeUtil.str2int(String.valueOf(result.get("count")));
				for(int i=0;i<count;i++) {
					boolean warning = (boolean) result.get("warning"+i);
					if(warning) {
						warnings.add(part);
						break;
					}
				}
			}
		}
		map.put("warnings", warnings);
		return map;
	}
}
